import { getApp, getAppWithoutAuth } from '../utils'
import md5 from 'md5'
import * as axios from 'axios'
import tcb from 'tcb-js-sdk'

/**
 * 检查是否登录了云平台。
 * @return {Promise<boolean>}
 */
export const hasLoginCloud = async () => {
  const loginState = await getAppWithoutAuth().auth().hasLoginState()

  return !!loginState
}

/**
 * 这里再次出现“跨域”问题。设置安全域名为localhost:3000就可以了。
 * @param username
 * @param password
 */
export const customLoginNew = async (
  username = '',
  password = '',
  flagMd5 = false
) => {
  if ('' === username || '' === password) {
    return { status: 1, msg: '用户名或者密码不能为空！' }
  }

  const loginState = await hasLoginCloud()
  // 已经登录云平台
  if (loginState) {
    try {
      const result = await loginCustomAccount(username, password, true)
      return { ...result }
    } catch (e) {
      return { status: 1, msg: e }
    }
  }

  // 没有登录云平台的就登录云平台
  const result = await loginCloud(username, password, flagMd5)
  const { status } = result

  if (status === 0) {
    // 登录云平台成功，接着登录自定义账户

    try {
      const result = await loginCustomAccount(username, password, true)
      return { status: 0, data: { ...result } }
    } catch (e) {
      return { status: 1, msg: e }
    }
  } else if (1 === status) {
    return result
  }
}
/**
 * 登录云平台
 * @return {Promise<void>}
 */
export const loginCloud = async (username, password, flagMd5 = false) => {
  const flag = await hasLoginCloud()

  return new Promise((resolve, reject) => {
    // 如果已经登录云平台。
    if (flag) {
      resolve({ status: 0, data: {} })
    } else {
      // 如果还没有登录
      const app = getApp()
      const authHeader = tcb.auth().getAuthHeader()

      password = flagMd5 ? md5(password) : password
      const sendData = {
        username,
        password,
        flagLoginCloud: true,
        flagLoginCustomAccount: false,
      }
      // { username: "admin", password: "21232f297a57a5a743894a0e4a801fc3", flagLoginCloud: true }

      axios({
        method: 'post',
        url: 'https://cake-shop-001-gppbo.service.tcloudbase.com/yczs-login',
        data: { ...sendData },
        headers: {
          ...authHeader,
        },
      })
        .then((res) => {
          const {
            data: { ticket, token, user },
          } = res.data
          /**
           * 这是新的方法
           * 这里是登录腾讯内部的逻辑
           * 我也不知道要登录什么
           */
          app
            .auth()
            .customAuthProvider()
            .signIn(ticket)
            .then(() => {
              resolve({ status: 0, data: {} })
            })
        })
        .catch((err) => {
          reject({ status: 1, msg: err })
        })
    }
  })
}
/**
 * 登录自定义账号
 * @param username
 * @param password
 * @param flagMd5 false 表示不需要md5加密
 * @return {Promise<null>}
 */
export const loginCustomAccount = async (
  username,
  password,
  flagMd5 = false
) => {
  const app = getApp()
  password = flagMd5 ? md5(password) : password

  return new Promise((resolve, reject) => {
    app
      .callFunction({
        name: 'custom-login',
        data: {
          username,
          password,
          flagLoginCloud: false,
          flagLoginCustomAccount: true,
        },
      })
      .then((res) => {
        const { data } = res.result
        resolve({ status: 0, data })
      })
      .catch((err) => {
        console.error(err)
        reject({ status: 1, msg: err })
      })
  })
}
